﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestTcpSockets.Plugin.Interface;
using System.Text.RegularExpressions;
using System.IO;

namespace TestTcpSockets.Plugin.System
{
    public class Record : INabPlugin
    {
        #region INabPlugin Members

        public bool HandleRequest(byte[] rawrequest, string request, global::System.IO.Stream reply)
        {
            if (request.Substring(9, 10) == "record.jsp")
            {
                Regex rx = new Regex("[^=]sn=(?<serialNumber>[^&]*)");
                Match m = rx.Match(request);
                if(m.Captures.Count>0)
                {
                    string serialnumber = m.Groups["serialNumber"].Captures[0].Value;
                    using (FileStream fs = new FileStream(@"D:\Temp\wav\" + serialnumber + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".wav", FileMode.Create))
                    {
                        int i = 0;
                        int cpt = 0;
                        foreach (byte b in rawrequest)
                        {
                            i++;
                            switch (cpt)
                            {
                                case 0 :
                                case 2 :
                                    {
                                        if (b == '\r') cpt++;
                                        else cpt = 0;
                                    }
                                    break;
                                case 1 :
                                case 3 :
                                    {
                                        if (b == '\n') cpt++;
                                        else if (b == '\r') cpt = 1;
                                        else cpt = 0;
                                    }
                                    break;
                            }
                            if(cpt==4) break;
                        }

                        fs.Write(rawrequest,i,rawrequest.Length-i);
                    }
                }
                
		
            }
            return false;
        }

        #endregion
    }
}
